package tests.read;

import static org.junit.Assert.*;

import java.util.ArrayList;

import model.Budget;
import model.BudgetFactory;
import model.Line;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import cc.test.bridge.BridgeInterface;
import cc.test.bridge.LineInterface;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

public class SublineQueryTest01
{
	Budget budget;
	BudgetFactory factory;
	Line line;
	Line s1;
	Line s2;

	@Before
	public void setUp() throws Exception
	{
		factory = new BudgetFactory();
		budget = (Budget) factory.create();
        budget.setName("Test budget");
        budget.setDescription("This is a test budget.");
        line = (Line) budget.createLine();
		budget.add(line);
		s1 = (Line) line.createSubline();
		s1.setNumber(1);
		s2 = (Line) line.createSubline();
		s2.setNumber(2);
		line.add(s1);
		line.add(s2);
		budget.commit();
	}

	@After
	public void tearDown() throws Exception
	{
		Helper.delete(s1, WorkletContext.getInstance());
		Helper.delete(s2, WorkletContext.getInstance());
		Helper.delete(line, WorkletContext.getInstance());
		Helper.delete(budget, WorkletContext.getInstance());
	}

	@Test
	public void test()
	{
		try{
			ArrayList<BasicDBObject> ors = new ArrayList<BasicDBObject>();
			ors.add(new BasicDBObject("entry.number", 1));
			ors.add(new BasicDBObject("entry.number", 2));
			BasicDBObject or = new BasicDBObject("$or", ors);
			String criteria = JSON.serialize(or);
			@SuppressWarnings("unchecked")
			ArrayList<BridgeInterface> results =  Helper.query(criteria, WorkletContext.getInstance());
		
			for(BridgeInterface bridge : results){
				if(bridge instanceof LineInterface){
					Integer number = ((Line) bridge).getNumber();
					if(number != 1 || number != 2){
						fail("Subline number query failed");
					}
				}
			}
		}catch(Exception e){
			fail("Subline number query failed with exception " + e);
		}
	}

}
